from apps.merchant.addr.baseViews import *

class AddrViewSet(BaseAddrViewSet):

    def get_queryset(self):
        _list = AddrDao().findAll().filter(user=self.request.user.id)
        return _list

    '''获取地址详情'''
    @action(methods=['post'], detail=False, url_path='getAddrInfo')
    def getAddrInfoAPI(self, request):
        params = getRequestParams(request)
        return Response(response_success(AddrModelSerializer(Addr.objects.get(id=params.get('addrId'))).data))

    '''获取默认地址详情'''
    @action(methods=['post'], detail=False, url_path='findDefaultAddr')
    def findDefaultAddrAPI(self, request):
        params = getRequestParams(request)
        _defaultAddrs = AddrDao().findAll().filter(user=request.user, default=True)
        if len(_defaultAddrs)>0:
            return Response(response_success(AddrModelSerializer(_defaultAddrs.first()).data))
        else:
            return Response(response_error('记录不存在'))

    '''新增'''
    @action(methods=['post'], detail=False, url_path='createAddr')
    def createAddrAPI(self, request):
        params = getRequestParams(request)
        # 如果存在默认地址，把默认地址全置false
        if params.get('default') is True:
            _defaultAddrs = Addr.objects.filter(user=request.user, default=True)
            if _defaultAddrs.exists():
                _defaultAddrs.update(default=False)
        # 如果用户新增收货地址
        if request.user.role.key == 'custom':
            params['user'] = request.user.id
        AddrDao().create(params)
        return Response(response_success('新增成功'))

    '''更新信息'''
    @action(methods=['post'], detail=False, url_path='updateAddr')
    def updateAddrAPI(self, request):
        params = getRequestParams(request)
        # 如果存在默认地址，把默认地址全置false
        if params.get('default') is True:
            _defaultAddrs = Addr.objects.filter(user=request.user, default=True)
            if len(_defaultAddrs)>0:
                _defaultAddrs.update(default=False)
        shopInfo = AddrDao().update(params.get('addrId'), params)
        return Response(response_success('修改成功'))